<?php
/*
 * Custom AppController for rdBloggery
 *
 * @author      gwoo <gwoo@rd11.com>
 * @version     0.10.8.2176
 * @license		OPPL
 *
 */
uses('sanitize');
class AppController extends Controller  {

	//Configuration
	var $layout = 'default';
	var $startpage = 'top';
//	var $useDbConfig = 'dev';
	
	var $components = array('rdAuth','rdCompany','Output','Valid','Prop','Session','Search','rdImage','Image','Email','Excel','Csv','ExcelWriter','Img','Encrypt','FileEncrtypt','Common');
	var $helpers = array('Html','appHtml','Javascript','Pagination','Fck');

	var $beforeFilter =	 array('setPageNum','checkAccess');
	//default is very restrictive, set on a per controller basis
	var $access = array ();	
	
	var $show;
	var $sortBy;
	var $direction;
	var $page;
	var $order;

	var $Sanitize;
					
   	function __construct()
	{
		parent::__construct();
		$this->Sanitize = &new Sanitize;
		$show = $this->Prop->getValue('config.pagination.show');
		$this->show = empty($_GET['show'])? $show: $this->Sanitize->paranoid($_GET['show']);
		$this->sortBy = empty($_GET['sort'])? 'created': $this->Sanitize->cleanValue($_GET['sort']);
		$this->direction = empty($_GET['direction'])? 'desc': $this->Sanitize->paranoid($_GET['direction']);
		$this->page = empty($_GET['page'])? '1': $this->Sanitize->paranoid($_GET['page']);
		$this->order = $this->modelClass.'.'.$this->sortBy.' '.strtoupper($this->direction);
		$this->setLastUpdateDate();
		$this->setPageNum();
		
		//@author wangyuhua 2012/4/10 start
		if($this->Session->check('rdAuth.id')) {
			$this->emailRealTime();
		}
		//@author wangyuhua 2012/4/10 end
	}
	
	/*
	 * @author wangyuhua 2012/4/10 start
	 * 实时check未读邮件
	 */
	function emailRealTime() {
		$email = new MemberEmailMsg();
		$sql = "
				select w.id,w.status
				from web_msg_info as w 
				join scout_msg_reaction_info as sr
				on w.scout_msg_id=sr.id
				and w.member_deleted is null and w.deleted is null 
				and sr.deleted is null and sr.member_deleted is null 
				and sr.status != '9'
				where w.member_id = " . $this->Session->read('rdAuth.id') . " and w.status = '0' and w.mail_from = '0'
				union 
				select s.id,sr.status
				from scout_msg_reaction_info as sr 
				join scout_msg_info as s 
				on sr.scout_id=s.id 
				and sr.deleted is null and sr.member_deleted is null and s.deleted is null 
				where now() >= sr.received 
				and sr.status != '9'
				and s.scout_status = '0'
				and sr.member_id = " . $this->Session->read('rdAuth.id') . " and sr.status = '0'
				union 
				select s.id,sr.status
				from notice_msg_reaction_info as sr 
				join notice_msg_info as s 
				on sr.notice_id=s.id 
				and sr.deleted is null and sr.member_deleted is null and s.deleted is null 
				where now() >= sr.received 
				and sr.status != '9'
				and s.notice_status = '0'
				and sr.member_id = " . $this->Session->read('rdAuth.id') . " and sr.status = '0'				
				";
		$emailFlg = $email->query($sql);
		$this->set('emailFlg',count($emailFlg));
	}
	// @author wangyuhua 2012/4/10 end 实时check未读邮件
	
	function setPageNum(){
		
		if($this->page>1){
			
			$s = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
			$this->Session->write('rurl',$s);
			
		}else{
			$s = $this->Session->read('rurl');
			
			$n = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
			
			$orurl = trim(substr($s,0,strcspn($s,"?")));
			$nrurl = trim(substr($n,0,strcspn($n,"?")));
			
				if(stristr($orurl,$nrurl)){
					$this->Session->write('rurl',$n);
				}
		}
		
		if(!empty($_COOKIE['PreURL'])){
			$curl = trim($_COOKIE['PreURL']);
			
			if($this->Session->check('rurl')){
				$rurl = trim($this->Session->read('rurl'));
			
				$crurl = trim(substr($curl,0,strcspn($curl,"?")));
				$srurl = trim(substr($rurl,0,strcspn($rurl,"?")));	
				if(stristr($crurl,$srurl)){
					$this->set('rurl',$rurl);
				}else{
					$this->set('rurl',$curl);
				}
			}else{
				$this->set('rurl',$curl);
			}
			
		
		}
		
		
	}
	
   	function checkAccess()
	{			
		return true;
		if (env('HTTP_X_REQUESTED_WITH'))
		{
			$this->layout = 'ajax';
		}
		//array of roles that is allowed to be an admin
		$this->rdAuth->admins = array('System','Admin','Staff');

		$this->rdAuth->set();//set local vars from session
		$this->rdCompany->set();//set company_info from session
		
		if (!$this->rdAuth->check($this->action, $this->access))
		{
			if(!empty($this->rdAuth->role)){
				$this->set('rdAuth',$this->rdAuth);
				$this->showError('role');
				exit;
			}
			else{
			  	$this->pageTitle = 'Permission Denied';
			  	$redirect = 'auth/login/';
				$pass = (!empty($this->params['pass'])) ? join('/',$this->params['pass']) : null;
			  	$this->redirect($redirect.$this->params['controller'].'/'.$this->params['action'].'/'.$pass);
			  	exit;				
			}
		}
		
		//从cookie中获得每页显示记录数
		if(!empty($_COOKIE['pagination_show'])){
			$this->show = $_COOKIE['pagination_show'];
		}
		//设置每页显示记录数
		if(!empty($this->data['PageShow']['PageSelect'])){
			$show = $this->data['PageShow']['PageSelect'];
			$show_array = explode(',',$this->Prop->getValue('config.page.show_select'));
			if(in_array($show,$show_array)){
				$this->show = $show;
				setcookie('pagination_show', $this->show,null,'/',null);
			}
			
		}
		
		$this->set('rdAuth',$this->rdAuth);
		$this->set('rdCompany',$this->rdCompany);
		$this->set('Encrypt',$this->Encrypt);
		return true;
	 }
	 
	 function checkAccess1($arg0,$arg1){
	 	if($arg0!=$arg1){
	 		$this->showError1('role');
	 	}
	 }
	 
	 function showError1($error,$arg0=null,$arg1=null,$arg2=null){
	 	$message = $this->Valid->tagErrorMsg($error,$arg0,$arg1,$arg2);
	 	$this->set('message',$message);
	 	$this->render('../errors/role_error');
	 	exit;
	 }
	 
	 function showError($error,$arg0=null,$arg1=null,$arg2=null){
	 	$message = $this->Valid->tagErrorMsg($error,$arg0,$arg1,$arg2);
	 	$this->set('message',$message);
	 	$this->render('../errors/index');
	 	exit;
	 }
	 
	 function show404($layout='default'){
	 	$this->render('../errors/error404',$layout);
	 	exit;
	 }
	 
	 function show4041($layout='default'){
	 	$this->render('../errors/errors404',$layout);
	 	exit;
	 }
	 
	 function show4042($layout='default'){
	 	$this->render('../errors/error404_1',$layout);
	 	exit;
	 }	 
	 
	 
	 function setPaging($style='ajax',$link,$count,$show=null,$page=null,$limit=null){
	 	$paging['style'] = $style;
		$paging['count']=$count;
		$paging['show'] = empty($show) ? array($this->show) : array($show);
		$paging['link'] = $link.'?page=';	
		$paging['page'] = empty($page) ? $this->page : $page;
		$paging['limit'] = empty($limit) ? $this->show : $limit;
		$paging['show_select'] = $this->pageShowSelect();
		$this->set('paging',$paging);
	 }
	 function delCookie($name) {
	 	$cookie_info_name = $name;
	  	$cookie_info_value = "";
	 	$cookie_info_time = time() - 60 * 60 * 24 * 30;
	 	setcookie($cookie_info_name, $cookie_info_value, $cookie_info_time, '/', '', false);
	 }
	 
	 function set_Cookie($name,$value,$day) {
	 	$cookie_info_name = $name;
	  	$cookie_info_value = $value;
	 	$cookie_info_time = time() + 60 * 60 * 24 * $day;
	 	setcookie($cookie_info_name, $cookie_info_value, $cookie_info_time, '/', '', false);
	 }
	 
	 function getMailTemplate($thtml,$data=null,$template_path = '../mail_template/')
     {
     	if(!empty($data)){
     		$this->set('mail_template',$data);	
     	}
        ob_start();
        $this->render($template_path.$thtml,'ajax');
        $template = ob_get_clean();
        return $template; 
     }
     
     function initPageLeft(){
     	$area_info = $this->SysParams->getArea();
		$tema_info = $this->SysParams->getTema();
		$this->set('area_info', $area_info);
		$this->set('tema_info', $tema_info);
     }
	 
	 function initPageCount($count,$unit1,$unit2,$midstr,$show1=null){
	 	if(empty($show1)){
	 		$show2=$this->show;
	 	}else{
	 		$show2=$show1;
	 	}
		$start_count=($this->page-1)*$show2+1;;
		$end_count=$show2;		
		if($this->page*$show2<=$count){
			$end_count=$this->page*$show2;
		}else{
			$end_count=$count;
		}
		return $count.$unit2.' '.$midstr.' '.$start_count.$unit1.'～'.$end_count.$unit1;
	}
	
	function pageShowSelect(){
		$show_select = $this->Prop->getValue('config.page.show_select');
		$show = split(',',$show_select);
		$select = array();
		foreach ($show as $key=>$val){
			$select[$val] = $val;
		}
		return $select;
	}
	
	function setLastUpdateDate(){
		$job = new Job();
		$job->belongsTo = array();
		$job->hasMany = array();
		$data = $job->find("\"Job\".\"deleted\" is null and to_char(\"Job\".\"public_start\",'YYYY-MM-DD HH24:MI:SS') < to_char(now(),'YYYY-MM-DD HH24:MI:SS') and" .
						   " \"Job\".\"public_close_date\" is null and" .
						   " (extract(epoch FROM now())- extract(epoch FROM \"Job\".\"public_end\") < 0) and" .
						   " \"Job\".\"job_status_id\"=1","approve_date","approve_date desc");
		$this->set('last_update_date',str_replace('-','/',substr($data['Job']['approve_date'],0,10)));
	}
	
	function _creatDir($fileDir) {
		$dirs = split("/", $fileDir);
		$path = ROOT . DS . APP_DIR . DS . WEBROOT_DIR . DS;
		foreach ($dirs as $dir) {
			$path .= DS . $dir;
			if (!file_exists($path)) {
				@ mkdir($path, 0777);
			}
		}
	}
	function initmobile()
	{
		$this->layout = 'mobile';
	}
}
?>